package ua.model;

import java.util.LinkedList;
import java.util.List;

import ua.common.XmlManager;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;

@XStreamAlias("tomcat-users")
public class TomcatUsersBean {
		
	@XStreamImplicit(itemFieldName="role")
	private List<RoleBean> roles;

	@XStreamImplicit(itemFieldName="user")
	private List<UserBean> users;

	public TomcatUsersBean() {
		roles = new LinkedList<RoleBean>();
		users = new LinkedList<UserBean>();
	}

	public List<RoleBean> getRoles() {
		if (roles == null) {
			roles = new LinkedList<RoleBean>();
		}
		return roles;
	}

	public List<UserBean> getUsers() {
		if (users == null) {
			users = new LinkedList<UserBean>();
		}
		return users;
	}
	
	public void setRoles(List<RoleBean> roles) {
		this.roles = roles;
	}

	public void setUsers(List<UserBean> users) {
		this.users = users;
	}

	public UserBean addUser(UserBean user) {
		getUsers().add(user);
		return user;
	}
	
	public RoleBean addRole(RoleBean role) {
		getRoles().add(role);
		return role;
	}

	public void removeRole(RoleBean role) {
		getRoles().remove(role);
	}
	
	public void removeUser(UserBean user) {
		getUsers().remove(user);
	}
	
	public void updateRolesFromStr() {
		for (UserBean user : getUsers())
		{
			String[] tab = user.getRolesStr().split(",");
			for (int i = 0; i < tab.length; i++) {
				RoleBean role = this.getRoleByName(tab[i]);
				if (role != null) {
					user.addRoleBean(role);
				}
			}
			//user.updateRolesFromStr(this);
		}
	}
	
	/*public void updateRolesFromStr(TomcatUsersBean tomcatUsers) {
		String[] tab = strRoles.split(",");
		for (int i = 0; i < tab.length; i++) {
			RoleBean role = tomcatUsers.getRoleByName(tab[i]);
			if (role != null) {
				addRoleBean(role);
			}
		}
	}*/
	
	/*public void updateRolesFromList() {
		for (UserBean user : getUsers()) {
			user.updateRolesFromList(this);
		}
	}*/
	
	public RoleBean getRoleByName(String roleName) {
	for (RoleBean role : getRoles()) {
		if (role.getRolename().equals(roleName)) {
			return role;
		}
	}
	return null;
	}
	
	public UserBean getUserByName(String userName) {
		for (UserBean user : getUsers()) {
			if (user.getUsername().equals(userName)) {
				return user;
			}
		}
		return null;
	}
	
	public void save()
	{
		XmlManager.getInstance().saveTomcatUser(this);
	}
}
